// ScrollPane.cpp: implementation of the ScrollPane class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "ScrollPane.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

IMPLEMENT_DYNAMIC(ScrollPane, Scroller)
IMPLEMENT_DYNAMIC(ScrollPaneViewport, AWTPanel)

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

ScrollPane::ScrollPane()
{
	m_offset = CPoint(0,0);
	remove(m_viewport);
//	delete m_viewport;
	Scroller::add("Scroll", m_viewport = new ScrollPaneViewport(this));
}

ScrollPane::~ScrollPane()
{

}

void ScrollPane::scrollTo(int x, int y)
{
	((ScrollPaneViewport*)m_viewport)->setOffset(CPoint(-x,-y));
}

CSize ScrollPane::getScrollAreaSize()
{
	AWTComponent* c = m_viewport->getComponent(0);
	if (c == NULL)
		return CSize(0,0);
	else
		return c->getMinimumSize();
}

void ScrollPane::reshape(int x, int y, int w, int h)
{
	invalidate(); 
	m_viewport->invalidate();
	AWTPanel::reshape(x,y,w,h);
}

AWTComponent* ScrollPane::add(AWTComponent* comp)
{
	if (m_viewport->countComponents() == 0)
	{
		return m_viewport->add(comp);
	}
	return comp;
}

void ScrollPaneViewport::doLayout()
{
	AWTComponent* c = getComponent(0);
	if (c == NULL)
		return;
	CSize szComp = c->getPreferredSize();
	CSize sz = getSize();
	int x, y, w, h;
	if (szComp.cx > sz.cx)
		x = 0;
	else
		x = (sz.cx - szComp.cx) / 2;
	if (szComp.cy > sz.cy)
		y = 0;
	else
		y = (sz.cy - szComp.cy) / 2;
	if ((x + szComp.cx) > sz.cx)
		w = sz.cx;
	else
		w = szComp.cx;
	if ((y + szComp.cy) > sz.cy)
		h = sz.cy;
	else
		h = szComp.cy;
	setBounds(x, y, w, h);
	c->setBounds(m_offset.x, m_offset.y, szComp.cx, szComp.cy);
}

void ScrollPaneViewport::setOffset(CPoint off)
{
	m_offset = off;
	AWTComponent* c = getComponent(0);
	if (c == NULL)
		return;
	c->setLocation(off);
}

